package com.suneast.suneaststore.modules.shopcart;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suneast.suneaststore.API;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.modules.common.CommonUtil;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.bean.goodsdetail.ItemShopCart2UpLoading;
import com.suneast.suneaststore.bean.personal.address.AddressBean;
import com.suneast.suneaststore.bean.shopcart.ItemGoodsInShopCart;
import com.suneast.suneaststore.bean.shopcart.ItemShopGoodsList;
import com.suneast.suneaststore.bean.shopcart.Member;
import com.suneast.suneaststore.bean.shopcart.ShopGoodsListBean;
import com.suneast.suneaststore.bean.shopcart.SubmitBillBean;
import com.suneast.suneaststore.modules.main.event.GotCartCount;
import com.suneast.suneaststore.modules.shopcart.event.CartEmptyEvent;
import com.suneast.suneaststore.modules.shopcart.event.DeleteGoodsResult;
import com.suneast.suneaststore.modules.shopcart.event.GotBillInfo;
import com.suneast.suneaststore.modules.shopcart.event.GotPayInfo;
import com.suneast.suneaststore.modules.shopcart.event.GotShopCartList;
import com.suneast.suneaststore.modules.shopcart.event.ItemGoodsSelectResult;
import com.suneast.suneaststore.modules.shopcart.event.SubmitBillResult;
import com.suneast.suneaststore.modules.shopcart.event.UpdateResult;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.suneast.suneaststore.util.net.RestClient;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class ShopCartHandler {
    static void requestShopCartList() {
        RestClient.builder()
                .url(API.SHOP_CART_LIST)
                .params("token", AccountManager.getToken())
                .success((response -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONObject dataJObj = rootJObj.getJSONObject("data");
                        JSONArray jArray = dataJObj.getJSONArray("list");
                        ArrayList<ItemShopGoodsList> goodsShopList = new ArrayList<>();
                        if (jArray != null && jArray.size() > 0) {
                            for (int i = 0, length = jArray.size(); i < length; i++) {
                                JSONObject jObj = jArray.getJSONObject(i);
                                int merchId = jObj.getIntValue("merchid");
                                String merchName = jObj.getString("merchname");
                                JSONArray goodsArray = jObj.getJSONArray("goods");
                                ArrayList<ItemGoodsInShopCart> itemList = new ArrayList<>();
                                if (goodsArray != null) {
                                    for (int j = 0, jLength = goodsArray.size(); j < jLength; j++) {
                                        ItemGoodsInShopCart item = new ItemGoodsInShopCart();
                                        JSONObject itemJObj = goodsArray.getJSONObject(j);
                                        item.setId(itemJObj.getIntValue("id"));
                                        item.setGoodsId(itemJObj.getIntValue("goodsid"));
                                        item.setMerchId(itemJObj.getIntValue("merchid"));
                                        item.setOptionId(itemJObj.getIntValue("optionid"));
                                        item.setTotal(itemJObj.getIntValue("total"));
                                        item.setHeight(itemJObj.getDoubleValue("height"));
                                        item.setWidth(itemJObj.getDoubleValue("width"));
                                        item.setVolume(itemJObj.getDoubleValue("volume"));
                                        item.setSelected(itemJObj.getIntValue("selected") == 1);
                                        item.setSuit(itemJObj.getIntValue("is_suit") == 1);
                                        item.setInstall(itemJObj.getIntValue("is_install") == 1);
                                        item.setCustom(itemJObj.getIntValue("is_custom") == 1);
                                        item.setMachining(itemJObj.getIntValue("is_machining") == 1);
                                        item.setMarketPrice(itemJObj.getDoubleValue("marketprice"));
                                        item.setMachiningPrice(itemJObj.getDoubleValue("machining_price"));
                                        item.setInstallPrice(itemJObj.getDoubleValue("install_price"));
                                        item.setTitle(itemJObj.getString("title"));
                                        item.setThumb(itemJObj.getString("thumb"));
                                        item.setPriceType(itemJObj.getIntValue("price_type"));
                                        item.setKg(itemJObj.getDoubleValue("kg"));
                                        item.setDispatchId(itemJObj.getIntValue("dispatchid"));
                                        item.setpCate(itemJObj.getIntValue("pcate"));
                                        item.setDiscount(itemJObj.getDoubleValue("discount"));
                                        item.setPrice(itemJObj.getDoubleValue("price"));
                                        item.setMaxHeight(itemJObj.getDoubleValue("maxheight"));
                                        item.setMaxWidth(itemJObj.getDoubleValue("maxwidth"));
                                        item.setMinBuy(itemJObj.getIntValue("minbuy"));
                                        item.setStock(itemJObj.getDoubleValue("stock"));
                                        item.setTotalNum(itemJObj.getDoubleValue("total_num"));
                                        item.setOptionTitle(itemJObj.getString("option_title"));
                                        item.setSuitPrice(itemJObj.getDoubleValue("suit_price"));
                                        item.setMachiningUnit(itemJObj.getString("machining_unit"));
                                        item.setInstallUnit(itemJObj.getString("install_unit"));
                                        item.setCoinDiscount(itemJObj.getIntValue("coin_discount"));
                                        item.setOldPrice(itemJObj.getDoubleValue("old_price"));
                                        item.setOldDiscount(itemJObj.getDoubleValue("old_discount"));
                                        item.setTotalMarketPrice(itemJObj.getDoubleValue("market_price"));
                                        item.setCoinRewardPercent(itemJObj.getDoubleValue("coin_reward_percent"));
                                        itemList.add(item);
                                    }
                                }
                                goodsShopList.add(new ItemShopGoodsList(merchId, merchName, itemList));
                            }
                        }
                        GotShopCartList gotEvent = new GotShopCartList(goodsShopList);
                        gotEvent.setTotalPrice(dataJObj.getDoubleValue("total_price"));
                        gotEvent.setTotalCount(dataJObj.getIntValue("total_count"));
                        gotEvent.setRealPrice(dataJObj.getDoubleValue("real_price"));
                        gotEvent.setCoinPrice(dataJObj.getDoubleValue("coin_price"));
                        gotEvent.setCoinRewardPrice(dataJObj.getIntValue("coin_reward_price"));
                        EventBus.getDefault().post(gotEvent);
                    } else {
                        EventBus.getDefault().post(new CartEmptyEvent());
                    }
                }))
                .failure(() -> {
                    LatteLogger.e("error", "requestShopCartList failure ");
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestShopCartList error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    static void updateCartItem(ItemGoodsInShopCart item) {
        RestClient.builder()
                .url(API.UPDATE_GOODS_IN_CART)
                .params("token", AccountManager.getToken())
                .params("id", item.getId())
                .params("total", item.getTotal())
                .params("optionId", item.getOptionId())
                .params("width", item.getWidth())
                .params("height", item.getHeight())
                .params("is_machining", item.isMachining() ? 1 : 0)
                .params("is_install", item.isInstall() ? 1 : 0)
                .params("is_suit", item.isSuit() ? 1 : 0)
                .params("is_custom", item.isCustom() ? 1 : 0)
                .success((String response) -> {
                    LatteLogger.json("test", response);
                    JSONObject rootObj = JSON.parseObject(response);
                    if (rootObj != null && rootObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new UpdateResult(Flag.Result.SUCCEED));
                    } else {
                        EventBus.getDefault().post(new UpdateResult(Flag.Result.FAILURE));
                    }
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault().post(new UpdateResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", "updateCartItem error code = " + code + "msg = " + msg);
                })
                .failure(() -> {
                    EventBus.getDefault().post(new UpdateResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", "updateCartItem failure");
                })
                .build()
                .post();
    }

    static void requestBill() {
        RestClient.builder()
                .url(API.CREATE_BILL)
                .params("token", AccountManager.getToken())
                .params("fromcart", 1)
                .success((response -> {
                    LatteLogger.json("test", response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        Member member = JSON.parseObject(dataObj.getJSONObject("member")
                                .toJSONString(), Member.class);
                        JSONObject addressObj = dataObj.getJSONObject("address");
                        AddressBean addressBean = null;
                        if (addressObj != null) {
                            addressBean = JSON.parseObject(dataObj.getJSONObject("address")
                                    .toJSONString(), AddressBean.class);
                        }
                        if (addressBean == null) {
                            addressBean = new AddressBean();
                        }
                        JSONObject goodsObj = dataObj.getJSONObject("goods");
                        JSONArray list = goodsObj.getJSONArray("list");
                        List<ShopGoodsListBean> shopGoodsListBeanList = JSON.parseArray(
                                list.toJSONString(), ShopGoodsListBean.class);

                        JSONObject createInfo = dataObj.getJSONObject("createInfo");
                        String createInfoStr = "";
                        if (createInfo != null) {
                            JSONObject jObj = createInfo.getJSONObject("goods");
                            if (jObj != null) {
                                createInfoStr = jObj.toJSONString();
                            }
                        }
                        LatteLogger.json("test", createInfoStr);
                        EventBus.getDefault().post(new GotBillInfo(
                                goodsObj.getDoubleValue("total_price"),
                                goodsObj.getIntValue("total_count"),
                                goodsObj.getDoubleValue("real_price"),
                                goodsObj.getDoubleValue("coin_price"),
                                goodsObj.getIntValue("coin_reward_price"),
                                addressBean,
                                member,
                                shopGoodsListBeanList,
                                createInfoStr
                        ));
                    } else {
                        JSONObject rootJObj = JSON.parseObject(response);
                        int code = rootJObj.getIntValue("code");
                        String msg = rootJObj.getString("msg");
                        LatteLogger.e("error", "requestBill code = "
                                + code + " msg = " + msg);
                    }
                }))
                .failure(() -> {
                    LatteLogger.e("error", "requestBill failure ");
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestBill error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    static void requestBill(ItemShopCart2UpLoading itemShopCart) {
        RestClient.builder()
                .url(API.CREATE_BILL)
                .params("token", AccountManager.getToken())
                .params("fromcart", 0)
                .params("goodsid", itemShopCart.getGoodsId())
                .params("optionId", itemShopCart.getOptionId())
                .params("is_suit", itemShopCart.isSuit() ? 1 : 0)
                .params("total", itemShopCart.getCount())
                .params("width", itemShopCart.getWidth())
                .params("height", itemShopCart.getHeight())
                .params("is_custom", itemShopCart.isCustom() ? 1 : 0)
                .success((response -> {
                    LatteLogger.json("test", response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        Member member = JSON.parseObject(dataObj.getJSONObject("member")
                                .toJSONString(), Member.class);
                        JSONObject addressObj = dataObj.getJSONObject("address");
                        AddressBean addressBean = null;
                        if (addressObj != null) {
                            addressBean = JSON.parseObject(addressObj.toJSONString(), AddressBean.class);
                        }
                        if (addressBean == null) {
                            addressBean = new AddressBean();
                        }
                        JSONObject goodsObj = dataObj.getJSONObject("goods");
                        JSONArray list = goodsObj.getJSONArray("list");
                        List<ShopGoodsListBean> shopGoodsListBeanList = JSON.parseArray(
                                list.toJSONString(), ShopGoodsListBean.class);

                        JSONObject createInfo = dataObj.getJSONObject("createInfo");
                        String createInfoStr = "";
                        if (createInfo != null) {
                            JSONObject jObj = createInfo.getJSONObject("goods");
                            if (jObj != null) {
                                createInfoStr = jObj.toJSONString();
                            }
                        }
                        EventBus.getDefault().post(new GotBillInfo(
                                goodsObj.getDoubleValue("total_price"),
                                goodsObj.getIntValue("total_count"),
                                goodsObj.getDoubleValue("real_price"),
                                goodsObj.getDoubleValue("coin_price"),
                                goodsObj.getIntValue("coin_reward_price"),
                                addressBean,
                                member,
                                shopGoodsListBeanList,
                                createInfoStr
                        ));
                    } else {
                        JSONObject rootObj = JSON.parseObject(response);
                        int code = rootObj.getIntValue("code");
                        String msg = rootObj.getString("msg");
                        LatteLogger.e("error", "requestBill code = "
                                + code + " msg = " + msg);
                    }
                }))
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestBill error code = "
                            + code + " msg = " + msg);
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestBill failure ");
                })
                .build()
                .post();
    }

    public static void selectOrUnSelectGoods(int id) {
        RestClient.builder()
                .url(API.SELECT_OR_DESELECT_GOODS_IN_CART)
                .params("token", AccountManager.getToken())
                .params("id", id)
                .success((response -> {
                    LatteLogger.json("test", response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        EventBus.getDefault().post(new ItemGoodsSelectResult(Flag.Result.SUCCEED,
                                dataObj.getIntValue("result"),
                                dataObj.getIntValue("id"),
                                dataObj.getDoubleValue("total_price"),
                                dataObj.getIntValue("total_count"),
                                dataObj.getDoubleValue("real_price"),
                                dataObj.getDoubleValue("coin_price"),
                                dataObj.getDoubleValue("coin_reward_price")
                        ));
                    } else {
                        EventBus.getDefault().post(new ItemGoodsSelectResult(Flag.Result.FAILURE, id));
                    }
                }))
                .failure(() -> {
                    EventBus.getDefault().post(new ItemGoodsSelectResult(Flag.Result.FAILURE, id));
                    LatteLogger.e("error", "selectOrUnSelectGoods failure ");
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault().post(new ItemGoodsSelectResult(Flag.Result.FAILURE, id));
                    LatteLogger.e("error", "selectOrUnSelectGoods error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    static void submitBill(SubmitBillBean bean) {
        LatteLogger.e("test", "submitBill: SubmitBillBean = " + bean.toString());
        RestClient.builder()
                .url(API.SUBMIT_BILL)
                .params("token", AccountManager.getToken())
                .params("use_lb_coin", bean.getUseLBCoin())
                .params("invoice_type", bean.getUseLBCoin())
                .params("invoice_info", bean.getInvoiceType())
                .params("invoice_no", bean.getInvoiceNumber())
                .params("dispatchtype", bean.getDispatchType())
                .params("fromcart", bean.getFromCart())
                .params("addressid", bean.getAddressId())
                .params("remark", bean.getRemark())
                .params("is_cl", bean.getHomeMeasure())
                .params("is_sj", bean.getDesign())
                .params("goods", bean.getGoodsListJsonStr())
                .success((response -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        int orderId = rootJObj.getJSONObject("data").getIntValue("id");
                        EventBus.getDefault().post(new SubmitBillResult(Flag.Result.SUCCEED, orderId));
                    } else {
                        EventBus.getDefault().post(new SubmitBillResult(Flag.Result.FAILURE,
                                0));
                        int code = rootJObj.getIntValue("code");
                        String msg = rootJObj.getString("msg");
                        LatteLogger.e("error", "submitBill code = "
                                + code + " msg = " + msg);
                    }
                }))
                .failure(() -> {
                    EventBus.getDefault().post(new SubmitBillResult(Flag.Result.FAILURE, 0));
                    LatteLogger.e("error", "submitBill failure fuck");
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault().post(new SubmitBillResult(Flag.Result.FAILURE, 0));
                    LatteLogger.e("error", "submitBill error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    static void deleteGoodsInCart(String ids) {
        RestClient.builder()
                .url(API.DELETE_GOODS_IN_CART)
                .params("token", AccountManager.getToken())
                .params("id", ids)
                .success((response -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        LatteLogger.e("test", "deleteGoodsInCart success");
                        EventBus.getDefault().post(new DeleteGoodsResult(Flag.Result.SUCCEED));
                    } else {
                        EventBus.getDefault().post(new DeleteGoodsResult(Flag.Result.FAILURE));
                        int code = rootJObj.getIntValue("code");
                        String msg = rootJObj.getString("msg");
                        LatteLogger.e("error", "deleteGoodsInCart code = "
                                + code + " msg = " + msg);
                    }
                }))
                .failure(() -> {
                    EventBus.getDefault().post(new DeleteGoodsResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", "deleteGoodsInCart failure ");
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault().post(new DeleteGoodsResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", "deleteGoodsInCart error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    static void requestPayInfo(int orderId) {
        RestClient.builder()
                .url(API.GET_BILL_DETAIL)
                .params("token", AccountManager.getToken())
                .params("id", orderId)
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        EventBus.getDefault().post(new GotPayInfo(
                                dataObj.getIntValue("id"),
                                dataObj.getString("ordersn"),
                                dataObj.getDoubleValue("oldprice"),
                                dataObj.getDoubleValue("price"),
                                dataObj.getDoubleValue("deduction_lb_coin")
                        ));
                    } else {
                        JSONObject rootObj = JSON.parseObject(response);
                        int code = rootObj.getIntValue("code");
                        String msg = rootObj.getString("msg");
                        LatteLogger.e("error", "requestPayInfo success but data null" +
                                " code = " + code + " msg = " + msg);
                    }
                })
                .error((code, msg) -> {
                    LatteLogger.e("error", " requestPayInfo error code = " + code + " msg = " + msg);
                })
                .failure(() -> {
                    LatteLogger.e("error", " requestPayInfo failure ");
                })
                .build()
                .post();
    }

    public static void requestCartCount() {
        RestClient.builder()
                .url(API.GET_CART_COUNT)
                .params("token", AccountManager.getToken())
                .success((String response) -> {
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        EventBus.getDefault()
                                .post(new GotCartCount(Flag.Result.SUCCEED,
                                        dataObj.getIntValue("count")));
                    }
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault()
                            .post(new GotCartCount(Flag.Result.FAILURE, 0));
                })
                .failure(() -> {
                    EventBus.getDefault()
                            .post(new GotCartCount(Flag.Result.FAILURE, 0));
                })
                .build()
                .post();
    }
}
